<template>
  <el-dialog :model-value="visible" :title="title" :before-close="cancelDialog" width="70%" custom-class="prewdialog"
    top="5vh">
    <el-row :gutter="20">
      <el-col :span="14">
        <div ref="videoPlayerWrap">
          <component
            :is="isPlayerVideo"
            ref="videoPlayerRef"
            :player-src="playerSrc"
            :player-mimetype="playerMimetype"
            @playEndHandle="autoPlayNextVideo"
            :key="dialogKey"
          />
          <!--<video-player ref="videoPlayerRef" :player-src="playerSrc" :player-mimetype="playerMimetype"
            @playEndHandle="autoPlayNextVideo" />-->
        </div>
      </el-col>
      <el-col :span="10" class="mediaprew">
        <div class="media-title">{{ toDialogData.name }}</div>
        <div class="media-cate">
          <span class="catename">{{ toDialogData.catname }}</span>
          <span class="mr10" v-for="(tag, index) in toDialogData.tags" :key="tag + index">{{ tag }}</span>
        </div>
        <div class="media-content">
          <div class="desc" ref="desc">{{ toDialogData.abstract }}</div>
          <a href="javascript:;" v-if="showMoreButton" @click="getMore()">详情</a>
        </div>
        <div class="media-stat">
          <!--<div class="icon-bell">
            <div>
              <el-button type="info" circle >
                <el-icon :size="24">
                  <bell />
                </el-icon>
              </el-button>
            </div>
            <div></div>
          </div>-->
          <div class="icon-zan">
            <div>
              <el-button type="info" circle>
                <i class="iconfont icon-guanzhuxinxingzan"></i>

              </el-button>
            </div>
            <div style="display:inline-block;text-align:center;margin-top:5px;">
              <span v-if="toDialogData.extends && toDialogData.extends.initlikeno">
                {{ toDialogData.extends.initlikeno }}
              </span>
              <span v-else>0</span>
              赞
            </div>
          </div>
          <div class="icon-goods" @click="handleOpenGoodsList">
            <div>
              <el-button type="info" circle>
                <el-icon>
                  <goods />
                </el-icon>
              </el-button>
            </div>
            <div style="display:inline-block;text-align:center;margin-top:5px;">
              商品
              <span>{{ goodsData.length }}</span>
            </div>
          </div>
        </div>
      </el-col>
      <el-col :span="24" class="mb20">
        <div class="series-title">
          直播间视频
        </div>
        <!-- <el-scrollbar> -->
        <div class="series-list" ref="scrollref" @scroll="getMoreVideo($event)">
          <div class="flex" ref="scrollinnerref">
            <div class="series-list-item" v-for="(series, indedx) in seriesData" :key="series.seriesid"
              @click="handleClickPlayVideo(series)" :class="{ 'video-active': activeSeriesid === series.seriesid }">
              <div>
                <el-image
                  :src="(series.thumbs && series.thumbs.length > 0) ? (series.thumbs[0].isself == 1 ? series.thumbs[0].viewurl + '&width=210&height=130' : series.thumbs[0].viewurl) : (toDialogData.thumbs && toDialogData.thumbs.length > 0 ? (toDialogData.thumbs[0].isself == 1 ? toDialogData.thumbs[0].viewurl + '&width=210&height=130' : toDialogData.thumbs[0].viewurl) : '')"
                  :initial-index="indedx" style="width: 210px;height:130px"/>
              </div>
              <div v-if="toDialogData['extends'] && toDialogData['extends']['ifshowseriesname'] > 0" class="txtclamp"
                style="padding:5px 5px 0;width:210px;box-sizing:border-box;">{{ series.name }}</div>
            </div>
            <!-- <div class="series-list-item">
            <el-button type="default" @click="handleGetMoreSeries" v-if="hasnextpage">更多视频</el-button>
          </div> -->
          </div>
        </div>
        <!-- </el-scrollbar> -->
      </el-col>
    </el-row>
    <div class="detailmore" v-if="isDetailMore">
      <el-icon class="btnclose" @click="handleclose()">
        <close />
      </el-icon>
      <div class="media-content">
        <div class="desc" ref="desc">{{ toDialogData.abstract }}</div>
      </div>
    </div>
    <goods-drawer
       ref="goodsDrawerRef"
      :goods-data="goodsData"
      :is-visible="isVisible"
      @closeGoodsDrawer="closeGoodsDrawer"
    />
  </el-dialog>
</template>

<script>
import { Goods } from '@element-plus/icons'
import { getSerierss } from "@/api/series/series";
import { ref, nextTick, reactive, defineAsyncComponent } from 'vue'
import { getMediaRelGoods } from "@/api/goods/relgoods";
import GoodsDrawer from "./MediaDetail/GoodsDrawer";

export default {
  name: "LiveRoomReview",
  components: { Goods,
    'VideoPlayer': defineAsyncComponent(() => import('@/components/player/VideoPlayer')),
    GoodsDrawer
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: ''
    },
    toDialogData: {
      type: Object,
      required: true
    }
  },
  emits: ['cancelDialog'],
  setup(props, context) {
    const videoPlayerWrap = ref(null)
    const playerSrc = ref('')
    const playerMimetype = ref('video/mp4')
    const videoPlayerRef = ref(null)
    const goodsData = ref([])
    const activeSeriesid = ref(Number)
    const hasnextpage = ref(false)
    const queryList = reactive({
      inuse: 1,
      page: 1,
      pagesize: 5,
      mediaid: props.toDialogData.mediaid
    })
    const isPlayerVideo = ref('VideoPlayer')
    const dialogKey = ref(Number)

    const desc = ref('')
    const isDetailMore = ref(false)
    const showMoreButton = ref(false)
    const scrollref = ref([])
    const scrollinnerref = ref([])
    const seriesData = ref([])

    const getMediaRelGoodsList = () => {
      getMediaRelGoods({ mediaid: props.toDialogData.mediaid }).then(response => {
        if (response.errcode == 0) {
          goodsData.value = response.data
        }
      })
    }
    const getSeriesList = () => {
      queryList.page = 1
      getSerierss(queryList).then(response => {
        if (response.errcode == 0) {
          seriesData.value = response.data.list
          hasnextpage.value = !!response.data.hasnextpage
          if (seriesData.value.length > 0) {
            if (seriesData.value[0].videos && seriesData.value[0].videos.length > 0) {
              playerSrc.value = seriesData.value[0].videos[0].playurl
              if (seriesData.value[0].videos[0].mimetype && !seriesData.value[0].videos[0].mimetype.includes('mp4')) {
                playerMimetype.value = seriesData.value[0].videos[0].mimetype
              }
            }
            activeSeriesid.value = seriesData.value[0].seriesid
          }
          handlePlayerVideo()
        }
      })
    }
    const handleClickPlayVideo = (series) => {
      dialogKey.value = new Date().getTime()
      playerSrc.value = ''
      playerMimetype.value = 'video/mp4'
      if (series.videos && series.videos.length > 0) {
        playerSrc.value = series.videos[0].playurl
        if (series.videos[0].mimetype && !series.videos[0].mimetype.includes('mp4')) {
          playerMimetype.value = series.videos[0].mimetype
        }
      }
      activeSeriesid.value = series.seriesid
      handlePlayerVideo()
      const index = seriesData.value.findIndex(series => series.seriesid === activeSeriesid.value)
      if (index > 0) {
        scrollref.value.scrollLeft = (index - 1) * 225
      } else {
        scrollref.value.scrollLeft = 0
      }
    }
    const cancelDialog = () => {
      nextTick(() => {
        videoPlayerRef.value.handleDisposePlayer()
      })
      context.emit('cancelDialog')
    }
    const handlePlayerVideo = () => {
      nextTick(() => {
        videoPlayerRef.value.init()
      })
    }
    const handleclose = () => {
      nextTick(() => {
        isDetailMore.value = false
      })
    }
    const getMore = () => {
      nextTick(() => {
        isDetailMore.value = true
      })
    }
    const isshowMoreButton = () => {
      nextTick(() => {
        const height = desc.value ? desc.value.clientHeight : 0;
        if (height > 50) {
          showMoreButton.value = true;
        } else {
          showMoreButton.value = false;
        }
      })
    }
    getMediaRelGoodsList()
    getSeriesList()
    isshowMoreButton()

    let getMoreFlag = false
    const handleGetMoreSeries = async () => {
      if (getMoreFlag){
        return
      }
      getMoreFlag = true

      queryList.page += 1
      await getSerierss(queryList).then(response => {
        if (response.errcode == 0) {
          seriesData.value = seriesData.value.concat(response.data.list)
          hasnextpage.value = !!response.data.hasnextpage
          getMoreFlag = false
        }
      })
    }
    const getMoreVideo = (e) => {
      let scrollLeft = e.target.scrollLeft // 滚动宽度
      let offsetWidth = scrollref.value.offsetWidth // 区域宽度
      let scrollWidth = scrollref.value.scrollWidth // 总宽度
      // console.log('scrollLeft:' + scrollLeft)
      // console.log('offsetWidth:' + offsetWidth)
      // console.log('total:' + eval(scrollLeft + offsetWidth))
      if (scrollWidth - (scrollLeft + offsetWidth) < 100) {
        if (hasnextpage.value) {
          handleGetMoreSeries()
        }

        // console.log('jisuan:' + eval(scrollWidth - (scrollLeft + offsetWidth)))
      }
    }
    // 自动播放下一个视频
    const autoPlayNextVideo = () => {
      // 获取当前视频在子集列表中的索引
      const index = seriesData.value.findIndex(series => series.seriesid === activeSeriesid.value)
      // 判断是否是列表中的最后一个
      if (index === seriesData.value.length - 1) {
        // 是最后一个，判断是否有下一页
        if (hasnextpage.value) {
          // 有下一页，加载下一页的数据
          handleGetMoreSeries()
          handleClickPlayVideo(seriesData.value[index + 1])
          // scrollref.value.scrollLeft = index * 225
        } else {
          // 没有下一页，提示没有下一页了还是播放第一个？
          handleClickPlayVideo(seriesData.value[0])
          // scrollref.value.scrollLeft = 0
        }
      } else {
        // 不是列表中的最后一个，在加载下一个视频
        handleClickPlayVideo(seriesData.value[index + 1])
        // scrollref.value.scrollLeft = index * 225
      }
    }

    const goodsDrawerRef = ref(null)
    const isVisible = ref(false)
    const handleOpenGoodsList = () => {
      isVisible.value = true
      console.log(goodsData.value);
      nextTick(() => {
        goodsDrawerRef.value.init()
      })
    }
    const closeGoodsDrawer  = () => {
      isVisible.value = false
    }
    return {
      cancelDialog,
      seriesData,
      getSeriesList,
      handleClickPlayVideo,
      videoPlayerWrap,
      playerMimetype,
      playerSrc,
      videoPlayerRef,
      goodsData,
      activeSeriesid,
      desc,
      showMoreButton,
      isshowMoreButton,
      isDetailMore,
      getMore,
      handleclose,
      handleGetMoreSeries,
      hasnextpage,
      scrollref,
      getMoreVideo,
      scrollinnerref,
      autoPlayNextVideo,
      isPlayerVideo,
      dialogKey,
      isVisible,
      handleOpenGoodsList,
      closeGoodsDrawer,
      goodsDrawerRef
    }
  }
}
</script>

<style scoped lang="scss">
::-webkit-scrollbar-track {
  background: rgba($color: #000000, $alpha: 0);
  border-radius: 0;
}

::-webkit-scrollbar {
  -webkit-appearance: none;
  width: 6px;
  height: 6px;
}

::-webkit-scrollbar-thumb {
  cursor: pointer;
  border-radius: 5px;
  background: rgba($color: #000000, $alpha: 0.15);
  transition: color 0.2s ease;
}

.prewdialog {
  position: relative;
}

.el-button .el-icon,
.iconfont {
  font-size: 24px;
}

.mediaprew {
  position: relative;

  .media-title {
    font-size: 28px;
  }

  .media-cate {
    margin: 10px 0;

    .catename {
      margin-right: 10px;
      font-size: 22px;
    }
  }

  .media-content {
    display: flex;
    align-items: flex-end;

    .desc {
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 3;
      overflow: hidden;
      width: 90%;
      text-align: justify;
    }

    >a {
      color: #409eff;
    }
  }

  .media-stat {
    position: absolute;
    bottom: 2px;
    margin-left: 20px;

    .el-button {
      margin: auto;
      width: 50px;
      height: 50px;
    }
  }

  .media-stat div {
    text-align: center;
    display: inline-grid;
    margin-right: 10px;
  }
}

.series-title {
  margin: 20px 0 10px;
  font-size: 26px;
}

.series-list {
  display: flex;
  width: 100%;
  overflow-x: auto;
  padding-bottom: 10px;
  margin-bottom: 20px;

  .series-list-item {
    cursor: pointer;
    margin-right: 15px;
    padding-bottom: 5px;
  }

  .series-empty {
    width: 210px;
    height: 0;
    visibility: hidden;
  }
}

.video-active {
  background-color: #f9f9f9;
  border: 1px solid #eee;
  color: #409eff;
}

.detailmore {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  width: 100%;
  background: rgba($color: #000000, $alpha: 0.7);
  z-index: 999;

  .media-content {
    margin-top: 50px;
    margin-right: 30px;
    float: right;
    width: 38%;

    .desc {
      color: #fff;
    }
  }

  .btnclose {
    position: absolute;
    top: 20px;
    right: 20px;
    font-size: 20px;
    color: #fff;
    cursor: pointer;
  }
}
</style>
<style>
/* .prewdialog{
    height:90vh;
  } */
</style>
